package com.esm.view;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.esm.app.MyApplication;
import com.esm.tool.BaseActivity;
import com.esm.tool.Config;
import com.esm.tool.Utils;
import com.esm.version.UpdateManager;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LoginActivity extends BaseActivity {
    RequestQueue mQueue = null;
    JsonObjectRequest mJsonObjectRequest = null;
    String riqi = "";
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    private EditText et_user, et_pwd;
    private TextView tv_commit, title_tv, tv_right_btn;
    private String userurl = MyApplication.SERVERPATH + "/Y502/Login1";
    private String username, password;
    private long firstTime = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        userurl = MyApplication.SERVERPATH + "/Y502/Login1";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        String sta = MyApplication.yy;
        updateActivity(sta, LoginActivity.class);
//		MyApplication.getSharedUserInfo().edit().putString("language", "vi").apply();
        setContentView(R.layout.activity_login);

        mQueue = MyApplication.getRequestQueue();
        username = MyApplication.getSharedUserInfo().getString("username", "admin");
        password = MyApplication.getSharedUserInfo().getString("password", "123");
        riqi = MyApplication.getSharedUserInfo().getString("riqi", "");
        MyApplication.path = MyApplication.getSharedUserInfo().getString("path", "");

        initView();
        MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, "").commit();

        //apk版本升级
        UpdateManager.getUpdateManager().checkAppUpdate(this, false);

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    time++;
                    if (time > 6) {
                        mHandler.sendEmptyMessage(ONMAIN);
                        break;
                    }
                }
            }
        }.start();

//        float scale = context.getResources().getDisplayMetrics().density;//1.5
//        int w =  (int) (2000 * scale + 0.5f);
//        int h =  (int) (1200 * scale + 0.5f);

    }

    int time = 0;
    public static final int ONMAIN = 1313;//到首页

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (ONMAIN == msg.what) {
                onMain();
            }
        }
    };

    void onMain() {
        if (MyApplication.getServersInfo().getString("serverip", "").equals("")) {
            showToast(getString(R.string.input_ipport));
            return;
        }
        username = et_user.getText().toString();
        if (username.trim().equals("")) {
            showToast(getString(R.string.input_username));
            return;
        }
        password = et_pwd.getText().toString();
        if (password.trim().equals("")) {
            showToast(getString(R.string.input_password));
            return;
        }
        login(username, password);
    }

    private void initView() {
        et_user = (EditText) findViewById(R.id.et_user);
        et_user.setText(username);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_pwd.setTypeface(Typeface.DEFAULT);
        et_pwd.setTransformationMethod(new PasswordTransformationMethod());
        et_pwd.setText(password);
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(R.string.Easement);
        tv_commit = (TextView) findViewById(R.id.tv_commit);
        tv_commit.setOnClickListener(this);
        tv_right_btn = (TextView) findViewById(R.id.tv_right_btn);
        tv_right_btn.setText(R.string.netsetting);
        tv_right_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_commit:
                if (MyApplication.getServersInfo().getString("serverip", "").equals("")) {
                    showToast(getString(R.string.input_ipport));
                    return;
                }
                username = et_user.getText().toString();
                if (username.trim().equals("")) {
                    showToast(getString(R.string.input_username));
                    return;
                }
                password = et_pwd.getText().toString();
                if (password.trim().equals("")) {
                    showToast(getString(R.string.input_password));
                    return;
                }
                login(username, password);
                break;
            case R.id.tv_right_btn:
                time = -9999;
                startActivity(new Intent(this, NetSettingActivity.class));
                break;
            default:
                break;
        }
    }

    private void login(String name, String pass) {

        boolean isConnected = Utils.toastIsNetworkConnected(context);
        if (isConnected) {
            showProgressBar();
            String url = userurl + "?name=" + name + "&&pass=" + pass;
            mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url,
                    null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    hideProgressBar();
                    parseData(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    hideProgressBar();
                    showToast(getString(R.string.network_error_try_again));
                }
            }
            );
            mQueue.add(mJsonObjectRequest);
        } else {
            showToast(getString(R.string.network_error_try_again));
            return;
        }
    }

    @Override
    protected void onDestroy() {
//	MyApplication.mylist.remove(this);
        super.onDestroy();
    }

    public void parseData(JSONObject response) {

        String access_token = "access_token";
        String result = response.optString("result");
        if (result == null || result.equals("") || result.equals("fail")) {
            MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, "").commit();
            MyApplication.getSharedUserInfo().edit().putString("password", "").commit();
            showToast(R.string.login_error);
            return;
        }
        MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, access_token).commit();
        MyApplication.getSharedUserInfo().edit().putString("username", username).commit();
        MyApplication.getSharedUserInfo().edit().putString("password", password).commit();
        //MyApplication.getSharedUserInfo().edit().putString("qx", result).commit();
        String[] s = result.split("#");
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("sn", s[0]);
        intent.putExtra("chanxian", s[1]);
        intent.putExtra("nnn", s[2]);

        if (s.length > 4) {
            long stime = Long.parseLong(s[4]); //一体机的时间 秒
            long now = System.currentTimeMillis() / 1000; //当前时间
            long xtime = stime - now;
            if (xtime > 60 || xtime < -60) {
                MyApplication.xtime = xtime;
            }
        }

        long thistime = MyApplication.xtime * 1000 + System.currentTimeMillis();
        String riqi1 = df.format(new Date(thistime));
        if (!riqi1.equals(riqi)) {
            MyApplication.getSharedUserInfo().edit().putString("nnn", "0").commit();
            MyApplication.getSharedUserInfo().edit().putString("riqi", riqi1).commit();
        }

        startActivity(intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) { //如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, getString(R.string.zayctc), Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;// 更新firstTime
                    return true;
                } else { //两次按键小于2秒时，退出应用
                    this.finish();
                    MyApplication.exit();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }
}
